package com.ashin.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sound.midi.Soundbank;
import java.util.HashSet;
import java.util.Set;


@RestController
public class RedisDeleteDemoController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/hello")
    public void hello() {
        redisTemplate.opsForValue().set("a", "zjh");
        System.out.println("success");


        Set<String> resultKeys = new HashSet<>();
        Cursor<String> keys = redisTemplate.scan(ScanOptions.scanOptions().match("*").count(1000).build());
        while (keys.hasNext()) {
            resultKeys.add(keys.next());
        }
        keys.close();
        System.out.println(resultKeys);

    }


    @GetMapping("/hello1")
    public void hello1() {
        redisTemplate.opsForValue().set("a", "zjh");
        System.out.println("success");


        Set<String> scan = scan("*");
        System.out.println(scan);
        System.out.println(scan.size());
    }


    @GetMapping("/init")
    public void init() {
        for (int i = 0; i < 200000; i++) {
            redisTemplate.opsForValue().set("a" + i, "i");
        }
    }

    @GetMapping("/delete")
    public void deleteAll() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("get_keys");
        Set<String> keys = scan("*");
        stopWatch.stop();


        stopWatch.start("delete_keys");

        keys.forEach(key->redisTemplate.delete(key));

        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
    }

    private Set<String> scan(String matchKey) {
        return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {

            Set<String> keySet = new HashSet<>();
            try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(matchKey).count(1000).build())) {
                while (cursor.hasNext()) {
                    keySet.add(new String(cursor.next()));
                }
            }

            return keySet;
        });
    }
}
